import { useEffect, useState } from 'react';
import styled from 'styled-components';

type WrapperProps = React.HTMLAttributes<HTMLDivElement> & {
  $h: number;
  $m: number;
  $s: number;
  $ms:number;
}

const Wrapper = styled.div<WrapperProps>`
  padding: 20%;
  display: grid;
  place-items: center;
  background-color: #555;

  & circle {
    fill: none;
    stroke: #77f;
    stroke-width: 1;
  }

  & circle.hours {
    stroke: #0ff;
    stroke-width: 7;
  }
  & circle.minutes {
    stroke: #07f;
    stroke-width: 3;
  }

  & circle.tick-mark {
    stroke-dasharray: .1 .9;
    stroke-dashoffset: .05;
  }

  & line {
    stroke: #fff;
    fill: #fff;
    stroke-linecap: round;
  }
  & line.second {
    stroke-width: 1;
    transform: ${({$s, $ms}) => `rotate(${$s * 6 + $ms * 6 / 1000}deg)`};
  }
  & line.minute {
    stroke-width: 3;
    transform: ${({$m}) => `rotate(${$m * 6}deg)`};
  }
  & line.hour {
    stroke-width: 7;
    transform: ${({$h, $m}) => `rotate(${$h * 30 + $m / 2}deg)`};
  }
`;

const Clock = () => {
  return (
    <svg viewBox='-120 -120 240 240'>
      <g fill='#61DAFB'>
        <circle cx="0" cy="0" r="95" pathLength={12} className='tick-mark hours'/>
        <circle cx="0" cy="0" r="94" pathLength={60} className='tick-mark minutes'/>

        <line x1="0" x2="0" y1="15" y2="-97" className='hand second' />
        <line x1="0" x2="0" y1="10" y2="-88" className='hand minute' />
        <line x1="0" x2="0" y1="5"  y2="-66" className='hand hour' />

        <circle cx="0" cy="0" r="3" />
      </g>
    </svg>
  );
};

export default function Demo () {
  const [current, setCurrent] = useState<Date>(new Date())

  useEffect(() => {
    const ref = setInterval(() => {
      setCurrent(new Date())
    }, 100)
    return (() => {
      if (!!ref) clearInterval(ref)
    })
  }, [])

  const props = {
    $h: current.getHours(),
    $m: current.getMinutes(),
    $s: current.getSeconds(),
    $ms:current.getMilliseconds(),
  }

  return (
    <Wrapper {...props}>
      <Clock />
    </Wrapper>
  )
}
